package com.tongtailian.www.stir.utils;

import android.androidlib.utils.ACache;
import android.androidlib.utils.JSONUtils;
import android.androidlib.utils.StringUtils;
import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothGatt;
import android.os.Handler;
import android.text.TextUtils;

import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleGattCallback;
import com.clj.fastble.callback.BleMtuChangedCallback;
import com.clj.fastble.callback.BleNotifyCallback;
import com.clj.fastble.callback.BleScanCallback;
import com.clj.fastble.callback.BleWriteCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.clj.fastble.scan.BleScanRuleConfig;
import com.clj.fastble.utils.HexUtil;
import com.tongtailian.www.stir.MyApplication;
import com.tongtailian.www.stir.R;
import com.tongtailian.www.stir.bean.BaseDataFram;
import com.tongtailian.www.stir.bean.BaseDataFramType;
import com.tongtailian.www.stir.bean.ConfigDataFram;
import com.tongtailian.www.stir.bean.DeviceKeyFram;
import com.tongtailian.www.stir.bean.DeviceModleFram;
import com.tongtailian.www.stir.bean.DeviceStateFram;
import com.tongtailian.www.stir.bean.DeviceUseFram;
import com.tongtailian.www.stir.bean.DevicesInfoBean;
import com.tongtailian.www.stir.bean.NumberBean;
import com.tongtailian.www.stir.bleinterface.MyBleDeviceModleCallBack;
import com.tongtailian.www.stir.bleinterface.MyBleDeviceStateCallBack;
import com.tongtailian.www.stir.bleinterface.MyBleGattCallback;
import com.tongtailian.www.stir.bleinterface.MyBleScanCallBack;
import com.tongtailian.www.stir.comm.ObserverManager;
import com.tongtailian.www.stir.utils.gson.GsonUtil;

import java.util.ArrayList;
import java.util.List;

import static com.clj.fastble.utils.HexUtil.formatHexString;

/**
 * @author liuml
 * @explain
 * @time 2021/3/21 18:57
 */
public class BleManageUtil {
    //蓝牙串口服务
    public static String SerialPortServiceClass_UUID = "6e400001-b5a3-f393-e0a9-e50e24dcca9e";//SPP服务UUID号
    //    public static String SerialPortServiceClass_UUID = "0000fff0-0000-1000-8000-00805f9b34fb";
    //特征码
//    public static String writeNoResponseUUID = "0000fff2-0000-1000-8000-00805f9b34fb";//发送
//    public static String readNotifyUUID = "0000fff1-0000-1000-8000-00805f9b34fb";//读取和通知操作
    public static String writeNoResponseUUID = "6e400002-b5a3-f393-e0a9-e50e24dcca9e";//发送
    public static String readNotifyUUID = "6e400003-b5a3-f393-e0a9-e50e24dcca9e";//读取和通知操作

    private BleDevice mBleDevice = null;

    private BleManager bleManager;
    private ConfigDataFram notiflyConfigData;
    private ProgressDialog progressDialog;
    //    private ImageView imgLoading;
    public boolean isConnect = false;//是否连接
    private Activity activity;
    MyBleGattCallback myBleGattCallback;//配置页面使用的

    public boolean isPlaying = false;//是否正在进行中
    public MyBleDeviceStateCallBack myBleDeviceStateCallBack;
    public MyBleDeviceModleCallBack myBleDeviceModleCallBack;
    private Handler handler = new Handler();

    private BleManageUtil() {
    }


    public void setMyBleDeviceStateCallBack(MyBleDeviceStateCallBack myBleDeviceStateCallBack) {
        this.myBleDeviceStateCallBack = myBleDeviceStateCallBack;
    }

    private static class BleManagerInstance {
        private static BleManageUtil instance = new BleManageUtil();
    }

    public static BleManageUtil getInstance() {
        return BleManagerInstance.instance;
    }

    public Handler getHandle(){
        return handler;
    }


    public void initData(Activity activity) {
        this.activity = activity;
        progressDialog = new ProgressDialog(activity);
        bleManager = BleManager.getInstance();
        BleScanRuleConfig scanRuleConfig = new BleScanRuleConfig.Builder()
//                .setServiceUuids(serviceUuids)      // 只扫描指定的服务的设备，可选
//                .setDeviceName(true, names)         // 只扫描指定广播名的设备，可选
//                .setDeviceMac(mac)                  // 只扫描指定mac的设备，可选
//                .setAutoConnect(isAutoConnect)      // 连接时的autoConnect参数，可选，默认false
                .setScanTimeOut(10000)              // 扫描超时时间，可选，默认10秒；小于等于0表示不限制扫描时间
                .build();

        BleManager.getInstance().initScanRule(scanRuleConfig);
    }


    /**
     * 通知 获取设备返回的数据- 发送信息后都从这里返回
     */
    public void notifly() {
        BleManager.getInstance().notify(
                mBleDevice,
                SerialPortServiceClass_UUID,
                readNotifyUUID,
                new BleNotifyCallback() {
                    @Override
                    public void onNotifySuccess() {
                        LogUtil.d("打开通知成功");
                    }

                    @Override
                    public void onNotifyFailure(final BleException exception) {
                        LogUtil.d("onNotifyFailure : " + exception.toString());
                    }

                    @Override
                    public void onCharacteristicChanged(byte[] data) {
                        BaseDataFram baseDataFram = new BaseDataFram();
                        String result = formatHexString(data);
                        LogUtil.d("设备返回的数据 onCharacteristicChanged: " + result);
                        PushLog.info("接收设备返回的数据 = "+result);
//                        tvTxtData.setText(result);
                        try {
                            baseDataFram.parseFrame(result);
                            LogUtil.d("设备返回的数据命令 baseDataFram  type: " + baseDataFram.type+
                                    "   设备返回的数据状态 baseDataFram  state:  "+ baseDataFram.state);
                            PushLog.info("设备返回的数据命令 baseDataFram  type: " + baseDataFram.type+
                                    "   设备返回的数据状态 baseDataFram  state:  "+ baseDataFram.state);
                            if(baseDataFram.state.equals(BaseDataFramType.success)){
                                LogUtil.i("设备返回数据成功 : " + baseDataFram.toString());
                                PushLog.info("设备返回数据成功 : " + baseDataFram.toString());
                                //ToastUtils.showCenter("发送数据成功");
                            }else{
                                LogUtil.i("设备返回数据错误 : " + baseDataFram.toString());
                                PushLog.info("设备返回数据错误 : " + baseDataFram.toString());
                                //ToastUtils.showCenter("发送数据失败");
                            }
                            switch (baseDataFram.type) {
                                case BaseDataFramType.version:
                                    //系统版本号
                                    LogUtil.d("系统版本号: " + result);
                                    DevicesInfoBean devicesInfoBean = new DevicesInfoBean("f1", "00");
                                    devicesInfoBean.parseFrame(result);
                                    LogUtil.d("解析版本信息 = " + devicesInfoBean.toString());
                                    break;
                                case BaseDataFramType.devicesState:
//                                    isPlaying = true;//判断设备运转中
                                    LogUtil.d("设备状态的数据: " + result);
                                    PushLog.info("设备状态的数据: " + result);
                                    DeviceStateFram deviceStateFram = new DeviceStateFram("00", "00");
                                    deviceStateFram.parseFrame(result);
                                    LogUtil.i("设备状态的数据 deviceStateFram: " + deviceStateFram.toString());
                                    PushLog.info("设备状态的数据 deviceStateFram: " + deviceStateFram.toString());
                                    if (myBleDeviceStateCallBack != null) {
                                        myBleDeviceStateCallBack.onDevicesState(deviceStateFram);
                                    }
                                    break;
                                case BaseDataFramType.devicesModle:
                                    LogUtil.d("设备模式的数据: " + result);
                                    PushLog.info("设备模式的数据: " + result);
                                    DeviceModleFram deviceModleFram = new DeviceModleFram("00", "00");
                                    deviceModleFram.parseFrame(result);
                                    if (myBleDeviceModleCallBack != null) {
                                        myBleDeviceModleCallBack.onDevicesState(deviceModleFram);
                                    }

                                    LogUtil.d("解析设备模式的数据 = " + deviceModleFram.toString());
                                    PushLog.info("解析设备模式的数据 = " + deviceModleFram.toString());
                                    break;
                                case BaseDataFramType.devicesUse:
                                    LogUtil.d("设备使用返回的数据 = " + result);
                                    PushLog.info("设备使用返回的数据 = " + result);
                                    DeviceUseFram deviceUseFram = new DeviceUseFram("00", "00");
                                    deviceUseFram.parseFrame(result);
                                    LogUtil.d("解析设备使用的数据 = " + deviceUseFram.toString());
                                    PushLog.info("解析设备使用的数据 = " + deviceUseFram.toString());
                                    break;
                                case BaseDataFramType.config:
                                    LogUtil.d("设备配置的数据 = " + result);
                                    PushLog.info("设备配置的数据 = " + result);
                                    notiflyConfigData = new ConfigDataFram("80", "00");
                                    notiflyConfigData.parseFrame(result);
                                    LogUtil.d("解析设备配置的数据 = " + notiflyConfigData.toString());
                                    PushLog.info("解析设备配置的数据 = " + notiflyConfigData.toString());
                                    if (myBleGattCallback != null) {
                                        myBleGattCallback.onConfigSuccess(notiflyConfigData);
                                    }
                                    break;
                                case BaseDataFramType.location:
                                    break;
                            }
                        } catch (Exception e) {
                            //（待验证）
                            if(StringUtils.isEmpty(baseDataFram.type)){
                                PushLog.info("解析设备返回的数据错误");
                                return;
                            }
                            PushLog.info("解析设备返回的数据错误 错误类型 = "+baseDataFram.type);
                            switch (baseDataFram.type) {
                                case BaseDataFramType.devicesState:
                                    PushLog.info("设备使用返回的数据错误 ");
                                    if(myBleDeviceStateCallBack!=null)
                                        myBleDeviceStateCallBack.onFail();
                                    break;
                                case BaseDataFramType.devicesModle:
                                    PushLog.info("设备模式返回的数据错误 ");
                                    if(myBleDeviceModleCallBack!=null)
                                        myBleDeviceModleCallBack.onFail();
                                    break;
                                case BaseDataFramType.config:
                                    PushLog.info("解析设备配置的数据错误 ");
                                    if(myBleGattCallback!=null)
                                        myBleGattCallback.onConfigFail();
                                    break;

                            }

                            /*if(myBleDeviceStateCallBack!=null)
                                myBleDeviceStateCallBack.onFail();
                            if(myBleGattCallback!=null)
                                myBleGattCallback.onConfigFail();
                            if(myBleDeviceModleCallBack!=null)
                                myBleDeviceModleCallBack.onFail();*/
                            LogUtil.e("数据解析失败 = " + e.getMessage());
                            PushLog.info("数据解析失败 = " + e.getMessage());
                        }
                        LogUtil.d("总共的解析的数据 : " + baseDataFram.getData());
                        PushLog.info("总共的解析的数据 : " + baseDataFram.getData());
                        LogUtil.d("onCharacteristicChanged : " + formatHexString(data));
                        PushLog.info("onCharacteristicChanged : " + formatHexString(data));
                    }
                });


    }

    public void getConfigDataFrame(int group, MyBleGattCallback callback) {
        myBleGattCallback = null;
        myBleGattCallback = callback;
        //group
        String s = addZeroForNumLeft(Integer.toHexString(group), 2);
        ConfigDataFram configDataFram2 = new ConfigDataFram(s, "");
//                ConfigDataFram configDataFram2 = new ConfigDataFram("00", "");
        String data2 = configDataFram2.getSendData();
        LogUtil.d("参数读取notifly : " + data2);
        PushLog.info("参数读取notifly : " + data2);
        LogUtil.d("参数读取configDataFram2 : " + JSONUtils.toJSON(configDataFram2));
        PushLog.info("参数读取configDataFram2 : " + JSONUtils.toJSON(configDataFram2));
        BleManageUtil.getInstance().writeData(data2);//发送数据
    }


    /**
     * 写入配置数据
     *
     * @param configDataFram
     */
    public void writeConfigFrame(ConfigDataFram configDataFram, MyBleGattCallback callback) {
        myBleGattCallback = null;
        myBleGattCallback = callback;
        if (notiflyConfigData == null) {
            ToastUtils.showCenter("数据未获取请重试");
            return;
        }
        final String data1 = configDataFram.createData(notiflyConfigData);
        LogUtil.d("写入配置参数数据 = " + data1);
        PushLog.info("写入配置参数数据 = " + data1);
        BleManageUtil.getInstance().writeData(data1);
    }

    /**
     * 发送设备按键 输入
     * @param type  1 确认 0 取消
     * @param
     */
    public void writeDeviceKeyFrame(int type) {
        //MyBleGattCallback callback
//        myBleGattCallback = null;
//        myBleGattCallback = callback;
        String data = "";
        if (type == 0) {
            data = "00020000";// 000200 取消
        } else if (type == 1) {
            data = "00010000";//000100 确认

        }
        DeviceKeyFram deviceKeyFram = new DeviceKeyFram("80", data);
        final String data1 = deviceKeyFram.getSendData();
        LogUtil.d("发送设备按键参数数据 = " + data1);
        PushLog.info("发送设备按键参数数据 = " + data1);
        BleManageUtil.getInstance().writeData(data1);
    }


    public ConfigDataFram getNotiflyConfigDataFrame() {
        if (notiflyConfigData != null) {
            return notiflyConfigData;
        }
        return null;
    }

    /**
     * 写入文件 只写入
     *
     * @param hex
     */
    public void writeData(String hex) {
        if (TextUtils.isEmpty(hex)) {
            return;
        }

        //（待验证）
        byte[] myhex = HexUtil.hexStringToBytes(hex);
        LogUtil.d("writeData写入文件最终发送数据: " + hex);
        //PushLog.info("writeData写入最终发送数据   延迟100毫秒发送数据 = "+hex);

        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                //PushLog.info("writeData写入最终发送数据   执行操作 = "+hex);
                /**
                 *要执行的操作
                 */
                BleManager.getInstance().write(
                        mBleDevice,
                        SerialPortServiceClass_UUID,
                        writeNoResponseUUID,
                        myhex,
                        new BleWriteCallback() {
                            @Override
                            public void onWriteSuccess(final int current, final int total, final byte[] justWrite) {
                                LogUtil.d("write success, current: " + current
                                        + " total: " + total
                                        + " justWrite: " + formatHexString(justWrite, true));
                                PushLog.info("writeData写入最终发送数据   延迟100毫秒发送数据成功 = "+formatHexString(justWrite, true));
                            }

                            @Override
                            public void onWriteFailure(BleException exception) {
                                LogUtil.d("onWriteFailure = " + exception.getDescription());
                                PushLog.info("writeData写入最终发送数据   延迟100毫秒发送数据失败 = "+exception.getDescription());
                                //ToastUtils.showCenter("失败: " + exception.getDescription());
                            }

                        });
            }
        }, 200);//3秒后执行Runnable中的run方法

    }


    public void connect(final BleDevice bleDevice) {

        BleManager.getInstance().connect(bleDevice, new BleGattCallback() {
            @Override
            public void onStartConnect() {
                PushLog.info("开始连接 ");
                // 开始连接
                progressDialog.show();
            }

            @Override
            public void onConnectFail(BleDevice bleDevice, BleException exception) {
                PushLog.info("连接失败 ");
                // 连接失败
//                imgLoading.clearAnimation();
//                imgLoading.setVisibility(View.INVISIBLE);
//                btnScan.setText(getString(R.string.start_scan));
                progressDialog.dismiss();
                ToastUtils.showCenter(activity.getString(R.string.connect_fail));
            }

            @Override
            public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) {
                LogUtil.d("onConnectSuccess = ");
                PushLog.info("连接成功 ");
                // 连接成功，BleDevice即为所连接的BLE设备
                progressDialog.dismiss();
                mBleDevice = bleDevice;
                isConnect = true;
                ObserverManager.getInstance().notifyConnectedObserver(bleDevice);
                LogUtil.i("onConnected","onConnectSuccess isConnect  " +isConnect);
//                devices.add(bleDevice);
                //获取某个已连接设备的BluetoothGatt
//                mBluetoothGatt = gatt;
                ACache.get(MyApplication.getAppInstance()).put("Bluetooth", ParcelableUtil.marshall(bleDevice));
//                mDeviceAdapter.setNewData(devices);
                //连接成功打开通知
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //PushLog.info("延迟100毫秒执行操作 notifly ");
                        /**
                         *要执行的操作
                         */
                        notifly();
                    }
                }, 200);//3秒后执行Runnable中的run方法
                //设置传输最大字符
                ConfitInit(bleDevice);
            }

            @Override
            public void onDisConnected(boolean isActiveDisConnected, BleDevice bleDevice, BluetoothGatt gatt, int status) {
                // 连接中断，isActiveDisConnected表示是否是主动调用了断开连接方法
                progressDialog.dismiss();
//                devices.remove(bleDevice);
//                mDeviceAdapter.setNewData(devices);
                isConnect = false;
                LogUtil.i("onConnected","onDisConnected isConnect  " +isConnect);

                if (isActiveDisConnected) {
                    //isActiveDisConnected表示是否是主动调用了断开连接方法
                    mBleDevice = null;
                    ToastUtils.showCenter(activity.getString(R.string.active_disconnected));
                } else {
                    //关闭蓝牙会出现这种情况
                    mBleDevice = null;
                    ToastUtils.showCenter("蓝牙已断开");
                    PushLog.info("蓝牙已断开");
//                    ToastUtils.showCenter(getString(R.string.disconnected));
                    ObserverManager.getInstance().notifyObserver(bleDevice);
                }
            }
        });
    }


    private void ConfitInit(BleDevice bleDevice) {
        LogUtil.d("设置传输最大字符 = "+BleManager.getInstance().getMaxConnectCount());
        BleManager.getInstance().setMtu(bleDevice, 244, new BleMtuChangedCallback() {
            @Override
            public void onSetMTUFailure(BleException exception) {
                // 设置MTU失败
                LogUtil.d("设置MTU失败= " + exception.getDescription() + " : \n" + exception.toString());
            }

            @Override
            public void onMtuChanged(int mtu) {
                // 设置MTU成功，并获得当前设备传输支持的MTU值
                LogUtil.d(" 设置MTU成功，并获得当前设备传输支持的MTU值 = " + mtu);
            }
        });
    }

    private List<BleDevice> devices = new ArrayList<>();

    public List<BleDevice> getDevices() {
        return devices;
    }


    public void startScan(final MyBleScanCallBack callBack) {
        BleManager.getInstance().scan(new BleScanCallback() {
            @Override
            public void onScanStarted(boolean success) {
                callBack.onScanStarted(success);
                // 开始扫描的回调
                LogUtil.d("开始扫描的回调 = " + success);
                devices.clear();

            }

            @Override
            public void onLeScan(BleDevice bleDevice) {
                super.onLeScan(bleDevice);
                callBack.onLeScan(bleDevice);
            }

            @Override
            public void onScanning(BleDevice bleDevice) {
                // 扫描到一个之前没有扫到过的设备的回调
//                LogUtil.d("扫描到一个之前没有扫到过的设备的回调 = " + bleDevice.toString());
                if(bleDevice.getName() != null && bleDevice.getName().contains("TTL")){
                    devices.add(bleDevice);
                    callBack.onScanning(bleDevice);
                    if (callBack != null) {
                        callBack.onLeScanList(devices);
                    }
                }

            }

            @Override
            public void onScanFinished(List<BleDevice> scanResultList) {
                // 扫描完成的回调，列表里将不会有重复的设备
//                LogUtil.d("扫描完成的回调 = " + scanResultList.size());
                List<BleDevice> scanResultListTTL = new ArrayList();
                for (BleDevice bleDevice : scanResultList) {
                    if (bleDevice.getName() != null && bleDevice.getName().contains("TTL")) {
                        scanResultListTTL.add(bleDevice);
                    }
                }
                callBack.onScanFinished(scanResultListTTL);

            }
        });
    }

    public void readDevicesState(MyBleDeviceStateCallBack callBack) {
        myBleDeviceStateCallBack = callBack;
        DeviceStateFram deviceStateFram = new DeviceStateFram("00", "00");
        //版本号设备  f100 返回的是 f100 + 字符串
        String sendData = deviceStateFram.getSendData();
        LogUtil.d("读取设备状态 = " + sendData);
        PushLog.info("读取设备状态 = " + sendData);
        writeData(sendData);
    }
    public void readDevicesModle(MyBleDeviceModleCallBack callBack) {
        myBleDeviceModleCallBack = callBack;
        DeviceModleFram deviceModleFram = new DeviceModleFram("01", "00");
        String sendData = deviceModleFram.getSendData();
        LogUtil.d("读取设备工作模式 = " + sendData);
        PushLog.info("读取设备工作模式 = " + sendData);
        writeData(sendData);
    }

    /**
     * 字符串右侧补零
     *
     * @param str
     * @param strLength
     * @return
     */
    public static String addZeroForNumLeft(String str, int strLength) {
        int strLen = str.length();
        if (strLen < strLength) {
            while (strLen < strLength) {
                StringBuffer sb = new StringBuffer();
                sb.append("0").append(str);// 左补0
                // sb.append(str).append("0");//右补0
                str = sb.toString();
                strLen = str.length();
            }
        }

        return str;
    }

    /**
     * @param group            选的是第几组
     * @param demoLocationList 样品座选了几个
     */
    public void beginDevices(int loopNum,int group, List<NumberBean> demoLocationList) {


        DeviceUseFram deviceUseFram = new DeviceUseFram();
//        String s = addZeroForNumLeft(Integer.toHexString(group), 2);
        deviceUseFram.setParam("01");//01是固定开启的
        deviceUseFram.setGroup(group);
        deviceUseFram.setLoop(loopNum);

        LogUtil.d("demoLocationList = " + GsonUtil.gsonString(demoLocationList));
        PushLog.info("连续模式  demoLocationList = " + GsonUtil.gsonString(demoLocationList));
        final int RED = 1;//0x1
        final int GREEN = 1 << 1;//0x2
        final int BLUE = 1 << 2;//0x4
        final int YELLOW = 1 << 3;// 0x8
        deviceUseFram.setWorkLocation1(demoLocationList.get(0).isSelect() ? RED : 0);
        deviceUseFram.setWorkLocation2(demoLocationList.get(1).isSelect() ? GREEN : 0);
        deviceUseFram.setWorkLocation3(demoLocationList.get(2).isSelect() ? BLUE : 0);
        deviceUseFram.setWorkLocation4(demoLocationList.get(3).isSelect() ? YELLOW : 0);
        String data = deviceUseFram.createData();
        LogUtil.d("连续模式 开始数据: " + GsonUtil.gsonString(deviceUseFram));
        LogUtil.d("连续模式 开始研磨发送数据 = " + data);
        PushLog.info("连续模式 开始研磨   数据 = "+GsonUtil.gsonString(deviceUseFram));
        PushLog.info("连续模式 开始研磨   发送数据 = "+data);
        BleManageUtil.getInstance().writeData(data);
        isPlaying = true;
    }

    /**
     * @param demoLocationList 样品座选了几个
     */
    public void beginDevicesForCustom(int loopNum,List<NumberBean> demoLocationList) {


        DeviceUseFram deviceUseFram = new DeviceUseFram();
//        String s = addZeroForNumLeft(Integer.toHexString(group), 2);
        deviceUseFram.setParam("07");//07是固定开启的
        deviceUseFram.setLoop(loopNum);

        LogUtil.d("自定义模式  demoLocationList = " + GsonUtil.gsonString(demoLocationList));
        final int RED = 1;//0x1
        final int GREEN = 1 << 1;//0x2
        final int BLUE = 1 << 2;//0x4
        final int YELLOW = 1 << 3;// 0x8
        deviceUseFram.setWorkLocation1(demoLocationList.get(0).isSelect() ? RED : 0);
        deviceUseFram.setWorkLocation2(demoLocationList.get(1).isSelect() ? GREEN : 0);
        deviceUseFram.setWorkLocation3(demoLocationList.get(2).isSelect() ? BLUE : 0);
        deviceUseFram.setWorkLocation4(demoLocationList.get(3).isSelect() ? YELLOW : 0);

        deviceUseFram.setGroup_workLocation1(demoLocationList.get(0).getGroup() > 0 ? demoLocationList.get(0).getGroup() : 0);
        deviceUseFram.setGroup_workLocation2(demoLocationList.get(1).getGroup() > 0 ? demoLocationList.get(1).getGroup() : 0);
        deviceUseFram.setGroup_workLocation3(demoLocationList.get(2).getGroup() > 0 ? demoLocationList.get(2).getGroup() : 0);
        deviceUseFram.setGroup_workLocation4(demoLocationList.get(3).getGroup() > 0 ? demoLocationList.get(3).getGroup() : 0);

        String data = deviceUseFram.createDataForCustom();
        LogUtil.d("自定义模式  开始数据: " + GsonUtil.gsonString(deviceUseFram));
        PushLog.info("自定义模式  开始数据: " + GsonUtil.gsonString(deviceUseFram));
        LogUtil.d("自定义模式  开始研磨发送数据 = " + data);
        PushLog.info("自定义模式  开始研磨发送数据 = " + data);
        BleManageUtil.getInstance().writeData(data);
        isPlaying = true;
    }

    /**
     * @param demoLocationList 样品座选了几个
     */
    public void createConfirmOrCancleData(int loopNum,List<NumberBean> demoLocationList) {


        DeviceUseFram deviceUseFram = new DeviceUseFram();
        deviceUseFram.setParam("10");//10是固定开启的
        deviceUseFram.setLoop(loopNum);

        LogUtil.d("demoLocationList = " + GsonUtil.gsonString(demoLocationList));
        PushLog.info("取消/新增 研磨罐  demoLocationList = " + GsonUtil.gsonString(demoLocationList));

        final int RED = 1;//0x1
        final int GREEN = 1 << 1;//0x2
        final int BLUE = 1 << 2;//0x4
        final int YELLOW = 1 << 3;// 0x8
        deviceUseFram.setWorkLocation1(demoLocationList.get(0).isSelect() ? RED : 0);
        deviceUseFram.setWorkLocation2(demoLocationList.get(1).isSelect() ? GREEN : 0);
        deviceUseFram.setWorkLocation3(demoLocationList.get(2).isSelect() ? BLUE : 0);
        deviceUseFram.setWorkLocation4(demoLocationList.get(3).isSelect() ? YELLOW : 0);

        String data = deviceUseFram.createConfirmOrCancleData();
        LogUtil.d("取消/新增 研磨罐 开始数据: " + GsonUtil.gsonString(deviceUseFram));
        PushLog.info("取消/新增 研磨罐 开始数据: " + GsonUtil.gsonString(deviceUseFram));
        LogUtil.d("取消/新增 研磨罐 开始研磨发送数据 = " + data);
        PushLog.info("取消/新增 研磨罐 开始研磨发送数据 = " + data);
        BleManageUtil.getInstance().writeData(data);
        isPlaying = true;
    }

    /**
     * 清洗转刀
     */
    public void wishKnife() {
        DeviceUseFram deviceUseFram = new DeviceUseFram("03", "00");
        String sendData1 = deviceUseFram.getSendData();
        LogUtil.d("清洗转刀数据: " + GsonUtil.gsonString(deviceUseFram));
        PushLog.info("清洗转刀数据: " + GsonUtil.gsonString(deviceUseFram));
        LogUtil.d("清洗转刀发送数据 = " + sendData1);
        PushLog.info("清洗转刀发送数据 = " + sendData1);
        BleManageUtil.getInstance().writeData(sendData1);
    }

    /**
     * 清洗管路
     */
    public void wishPipe() {
        DeviceUseFram deviceUseFram = new DeviceUseFram("04", "00");
        String sendData1 = deviceUseFram.getSendData();
        LogUtil.d("清洗管路数据: " + GsonUtil.gsonString(deviceUseFram));
        PushLog.info("清洗管路数据: " + GsonUtil.gsonString(deviceUseFram));
        LogUtil.d("清洗管路发送数据 = " + sendData1);
        PushLog.info("清洗管路发送数据 = " + sendData1);
        BleManageUtil.getInstance().writeData(sendData1);
    }

    /**
     * 更换转刀
     */
    public void changeKnife() {
        DeviceUseFram deviceUseFram = new DeviceUseFram("05", "00");
        String sendData1 = deviceUseFram.getSendData();
        LogUtil.d("更换转刀数据: " + GsonUtil.gsonString(deviceUseFram));
        PushLog.info("更换转刀数据: " + GsonUtil.gsonString(deviceUseFram));
        LogUtil.d("更换转刀发送数据 = " + sendData1);
        PushLog.info("更换转刀发送数据 = " + sendData1);
        BleManageUtil.getInstance().writeData(sendData1);
    }

    public void stopDevices() {
        isPlaying = false;
        DeviceUseFram deviceUseFramStop = new DeviceUseFram("00", "00");
        String sendData1 = deviceUseFramStop.getSendData();
        LogUtil.d("停止数据: " + GsonUtil.gsonString(deviceUseFramStop));
        PushLog.info("停止数据: " + GsonUtil.gsonString(deviceUseFramStop));
        LogUtil.d("停止研磨发送数据 = " + sendData1);
        PushLog.info("停止研磨发送数据 = " + sendData1);
        BleManageUtil.getInstance().writeData(sendData1);
    }


}
